package com.yumeng.common.api;

import io.swagger.v3.oas.annotations.media.Schema;
import org.apache.commons.collections4.CollectionUtils;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;

import static java.util.stream.Collectors.toList;

/**
 * 分页返回数据结构
 * @author wxd
 * @date 2021/12/6 11:26
 */
@Schema(name = "PageData<T>", description = "分页结果对象")
public class PageData<T> implements Serializable {

    @Schema(description = "总行数")
    private long total = 0;
    @Schema(description = "数据列表")
    private List<T> records = Collections.emptyList();
    @Schema(description = "页码")
    private long pageNum;
    @Schema(description = "页大小")
    private long pageSize;

    public PageData() {}

    public PageData(long total, List<T> records, long pageNum, long pageSize) {
        this.total = total;
        this.records = records;
        this.pageNum = pageNum;
        this.pageSize = pageSize;
    }

/*    public PageData(IPage<T> page) {
        this.total = page.getTotal();
        this.records = page.getRecords();
        this.pageNum = page.getCurrent();
        this.pageSize = page.getSize();
    }

    public PageData(IPage page, List<T> records) {
        this.total = page.getTotal();
        this.records = records;
        this.pageNum = page.getCurrent();
        this.pageSize = page.getSize();
    }*/

    public long getTotal() {
        return total;
    }

    public void setTotal(long total) {
        this.total = total;
    }

    public List<T> getRecords() {
        return records;
    }

    public PageData<T> setRecords(List<T> records) {
        this.records = records;
        return this;
    }

    public long getPageNum() {
        return pageNum;
    }

    public void setPageNum(long pageNum) {
        this.pageNum = pageNum;
    }

    public long getPageSize() {
        return pageSize;
    }

    public void setPageSize(long pageSize) {
        this.pageSize = pageSize;
    }

    /**
     * 泛型转换
     *
     * @param mapper
     * @param <R>
     * @return
     */
    public  <R> PageData<R> convert(Function<? super T, ? extends R> mapper) {
        List<R> collect = this.getRecords().stream().map(mapper).collect(toList());
        return ((PageData<R>) this).setRecords(collect);
    }

    /**
     * 是否包含数据
     *
     * @return
     */
    public boolean hasData(){
        return CollectionUtils.isNotEmpty(this.records);
    }
}
